package com.chen.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.chen.dto.UserDto;
import com.chen.entity.User;
import com.chen.service.MemberReceiveAddressService;
import com.chen.service.UserService;
import com.chen.vo.AddressVo;
import com.chen.vo.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

import static com.chen.constant.RedisConstants.MALL_ADDRESS;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author cws
 * @since 2024-11-24
 */
@RestController
@RequestMapping("/mall/user")
public class UserController {


    @Resource
    UserService userService;

    @Resource
    MemberReceiveAddressService addressService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/getUserInfo")
    public Result getUserInfo(@RequestHeader("Authorization") String token) {
        return userService.getUserInfo(token);
    }

    @PutMapping("/updateUser")
    public Result updateUserInfo(@RequestBody UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        userService.updateById(user);
        return Result.success();
    }

    @GetMapping("/area")
    @ApiOperation("获取省市区三级联动列表")
    public Result treeList() {
        if (redisTemplate.hasKey(MALL_ADDRESS)) {
            String res = redisTemplate.opsForValue().get(MALL_ADDRESS);
            List<AddressVo> addressVos = JSONUtil.toList(res, AddressVo.class);
            return Result.success(addressVos);
        }
        List<AddressVo> addressVos = addressService.treeList();
        redisTemplate.opsForValue().set(MALL_ADDRESS, JSONUtil.toJsonStr(addressVos));
        return Result.success(addressVos);
    }


}

